package com.example.demo;

import com.github.rcaller.rstuff.RCaller;
import com.github.rcaller.rstuff.RCallerOptions;
import com.github.rcaller.rstuff.RCode;
import com.github.rcaller.rstuff.RProcessStartUpOptions;
import com.github.rcaller.rstuff.FailurePolicy;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@CrossOrigin
@RestController
public class HelloController {

    private static final String LIBS_DIR = "/www/wwwroot/www.shenai.site/files/";

    @GetMapping("/")
    public String sayHello() {
        return "hello";
    }

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("files") MultipartFile[] files) {
        // Save files to the specified directory
        File dir = new File(LIBS_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        for (MultipartFile file : files) {
            System.out.println("文件名称: " + file.getOriginalFilename());
            System.out.println("文件大小: " + file.getSize() + " bytes");
            System.out.println("文件类型: " + file.getContentType());
            System.out.println();
            try (FileOutputStream fos = new FileOutputStream(new File(LIBS_DIR + file.getOriginalFilename()))) {
                fos.write(file.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件保存失败: " + e.getMessage());
            }
        }

        // Check if there are 4 files in the directory
        File[] uploadedFiles = dir.listFiles();
        if (uploadedFiles != null && uploadedFiles.length == 4) {
            // If there are 4 files, run the R script
            ResponseEntity<String> response = runRScript(LIBS_DIR);
            if (response.getStatusCode() == HttpStatus.OK) {
                // Delete files in the directory
                deleteFilesInDirectory(LIBS_DIR);
            }
            return response;
        } else {
            return ResponseEntity.status(HttpStatus.OK).body("上传成功");
        }
    }

    private ResponseEntity<String> runRScript(String libsDir) {
        try {
            // 创建 RCaller 和 RCode 对象
            RCallerOptions options = RCallerOptions.create(
                    "/root/anaconda3/envs/test/bin/Rscript", // 指定 Rscript 可执行文件路径
                    "/root/anaconda3/envs/test/bin/R", // 指定 R 解释器路径
                    FailurePolicy.RETRY_5, // 设置失败策略
                    Long.MAX_VALUE, // 最大等待时间
                    100L, // 初始等待时间
                    RProcessStartUpOptions.create() // 默认启动选项
            );


            RCaller caller = RCaller.create(options);
            RCode code = RCode.create();

            // 设置 R 脚本文件路径
            String rFilePath = "/www/wwwroot/www.shenai.site/test.R";

            // 打印当前 R 解释器的版本和路径
            code.addRCode("cat('当前 R 解释器版本: ', R.version.string, '\\n')");
            code.addRCode("cat('R 解释器路径: ', R.home(), '\\n')");

            // 加载并执行 R 文件
            code.R_source(rFilePath);
            code.addRCode("sink('output.txt')"); // 重定向输出到文件
            code.addRCode("source('" + rFilePath + "')");
            code.addRCode("sink()"); // 恢复输出到控制台
            caller.setRCode(code);

            // 执行 R 代码
            caller.runOnly();

            // 从文件中读取 R 输出结果的最后一行
            String lastLine = "";
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("output.txt")))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    lastLine = line;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("读取 R 输出文件错误: " + e.getMessage());
            }

            // 根据最后一行的内容输出 IM2 或 IM4
            String result;
            if (lastLine.contains("IM2")) {
                result = "IM2";
            } else if (lastLine.contains("IM4")) {
                result = "IM4";
            } else {
                result = "未知结果: " + lastLine;
            }

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("执行 R 脚本错误: " + e.getMessage());
        }
    }

    private void deleteFilesInDirectory(String dirPath) {
        File dir = new File(dirPath);
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (!file.isDirectory()) {
                    file.delete();
                }
            }
        }
    }
}
